package com.xsd.prc;

/**
 * @Description: 线程的交互 wait await 练习
 * @Author: zhoufuzong
 * @Created: 2020-12-30 21:59:05
 * @Version: 1.1.0
 */


class AirCondition{
    private  int number=0;

//    private Lock lock = new ReentrantLock();

    public synchronized void add() throws InterruptedException {
//        lock.lock();
//        try {

            // 判断\
            while (number !=0) {
                this.wait();
            }
            // 干活
            number++;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            // 通知
           this.notifyAll();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            lock.unlock();
//        }
    }

    public synchronized void dec() throws InterruptedException {
//        lock.lock();
//        try {
          // 判断
            while (number == 0) {
                this.wait();  // wait notify 只能被同步监听锁对象对象调用，否则报IllegalMonitorStateException..
            }
            // 干活
           number--;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            // 通知
            this.notifyAll();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            lock.unlock();
//        }
    }
}
public class ThreadNotifyDemo {
    public static void main(String[] args) {
        AirCondition airCondition =new AirCondition();

        new Thread(()->{
            for (int i = 0; i <10 ; i++) {

                try {
                    airCondition.add();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition.dec();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        },"B").start();

    }
}
